<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :defaults.sync="defaults"
      :data="data"
      :page.sync="page"
      ref="crud"
      @row-del="rowDel"
      v-model="form"
      :permission="permissionList"
      @row-update="rowUpdate"
      @row-save="rowSave"
      :before-open="beforeOpen"
      :search.sync="search"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.eventRegister_delete" @click="handleDelete">删 除 </el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot-scope="scope" slot="menu">
        <el-button type="text" icon="el-icon-view" size="small" v-if="permission.eventRegister_view" @click="handleDetail(scope.row, scope.index)">详情</el-button>
        <el-button
          type="text"
          icon="el-icon-edit"
          size="small"
          v-if="permission.eventRegister_edit && scope.row.status === 1"
          @click="$refs.crud.rowEdit(scope.row, scope.index)"
          >编辑</el-button
        >
        <el-button type="text" icon="el-icon-s-tools" size="small" v-if="scope.row.status === 1" @click.stop="handleManages(scope.row, scope.index)">处理</el-button>
      </template>

      <template slot-scope="{ row }" slot="status">
        <span v-if="row.status == 1" class="stateWords-warning">待处理</span>
        <span v-else class="stateWords-success">已处理</span>
      </template>

      <template slot-scope="" slot="principalNameSearch">
        <el-input placeholder="请选择 事件负责人" readonly="true" v-model="search.principalName">
          <el-button slot="append" icon="el-icon-search" @click="openUserCommonModal({ type: 'principalName' })"></el-button>
        </el-input>
      </template>
      <template slot-scope="" slot="creatorSearch">
        <el-input placeholder="请选择 发起人" readonly="true" v-model="search.creator">
          <el-button slot="append" icon="el-icon-search" @click="openUserCommonModal({ type: 'creator' })"></el-button>
        </el-input>
      </template>
    </avue-crud>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
    <el-dialog title="事件处理" :visible.sync="manageDialog.visible" append-to-body :show-close="false" width="60%" top="5vh">
      <avue-form ref="manageForm" v-model="manageDialog.form" :option="manageDialog.option" @submit="handleSubmit" @reset-change="handleReset"> </avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" v-preventReClick @click="manageSave">保存</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="manageCancel">取消</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, remove, update, add, handleEvent } from '@/api/desk/eventRegister';
import { mapGetters } from 'vuex';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';

export default {
  name: 'eventRegister',
  components: {
    GlobalModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'EVENT_REGISTER',
      rowData: {},
      manageDialog: {
        visible: false,
        form: {
          handlerName: '',
          handlerId: ''
        },
        option: {
          row: true,
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: '处理人',
              prop: 'handlerName',
              span: 12,
              type: 'search',
              searchType: 'input',
              appendClick: () => {
                this.openUserCommonModal({
                  type: 'manageClr'
                });
              },
              rules: [
                {
                  required: true,
                  message: '请输入处理人',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '处理时间',
              prop: 'handleTime',
              type: 'datetime',
              span: 12,
              format: 'yyyy-MM-dd HH:mm:ss',
              valueFormat: 'yyyy-MM-dd HH:mm:ss',
              rules: [
                {
                  required: true,
                  message: '请输入处理时间',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '处理结果',
              prop: 'handleResult',
              span: 24,
              rowSpan: 4,
              type: 'textarea',
              maxlength: 200,
              showWordLimit: true,
              rules: [
                {
                  required: true,
                  message: '请输入处理结果',
                  trigger: 'blur'
                }
              ]
            }
          ]
        }
      },
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      search: {
        principalName: '',
        creator: ''
      },
      option: {
        height: 'auto',
        calcHeight: 30,
        dialogWidth: 950,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        searchLabelWidth: 90,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        viewBtnText: '详情',
        viewTitle: '详情',
        selection: true,
        excelBtn: false,
        dialogClickModal: false,
        columnBtn: false,
        column: [
          {
            label: '事件维度',
            prop: 'dimension',
            span: 24,
            row: true,
            search: true,
            type: 'select',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            dicData: [
              { label: '工厂', value: '工厂' },
              { label: '车间', value: '车间' },
              { label: '产线', value: '产线' }
            ]
          },
          {
            label: '事件标题',
            prop: 'title',
            search: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false
          },
          {
            label: '事件负责人',
            prop: 'principalName',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            search: true
          },
          {
            label: '截止时间',
            prop: 'searchDeadlineTime',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            type: 'datetime',
            search: true,
            searchLabelWidth: 80,
            searchType: 'datetimerange',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间',
            hide: true,
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: '截止时间',
            prop: 'deadlineTime',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            type: 'date',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: '状态',
            prop: 'status',
            width: 80,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            search: true,
            type: 'select',
            dicData: [
              { label: '待处理', value: 1 },
              { label: '已处理', value: 2 }
            ]
          },
          {
            label: '处理人',
            prop: 'handlerName',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false
          },
          {
            label: '处理时间',
            prop: 'handleTime',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            type: 'date',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: '发起人',
            prop: 'creator',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            search: true
          },
          {
            label: '发起时间',
            prop: 'createTime',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            type: 'date',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          }
        ],
        group: [
          {
            label: '事件维度',
            prop: 'dimension',
            labelWidth: 100,
            icon: 'el-icon-edit-outline',
            column: [
              {
                label: '事件维度',
                prop: 'dimension',
                span: 12,
                type: 'select',
                dicData: [
                  { label: '工厂', value: '工厂' },
                  { label: '车间', value: '车间' },
                  { label: '产线', value: '产线' }
                ],
                control: (val, form) => {
                  if (val == '车间') {
                    return {
                      workshopName: {
                        display: true
                      },
                      lineName: {
                        display: false
                      }
                    };
                  } else if (val == '产线') {
                    return {
                      workshopName: {
                        display: false
                      },
                      lineName: {
                        display: true
                      }
                    };
                  } else {
                    return {
                      workshopName: {
                        display: false
                      },
                      lineName: {
                        display: false
                      }
                    };
                  }
                },
                rules: [
                  {
                    required: true,
                    message: '请输入事件维度',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '车间',
                prop: 'workshopName',
                type: 'search',
                searchType: 'input',
                appendClick: () => {
                  this.openUserCommonModal({
                    type: 'workshop'
                  });
                },
                span: 12
              },
              {
                label: '产线',
                prop: 'lineName',
                type: 'search',
                searchType: 'input',
                appendClick: () => {
                  this.openUserCommonModal({
                    type: 'line'
                  });
                },
                span: 12
              }
            ]
          },
          {
            label: '事件信息',
            prop: 'sjxx',
            icon: 'el-icon-edit-outline',
            labelWidth: 100,
            column: [
              {
                label: '事件标题',
                prop: 'title',
                span: 12,
                rules: [
                  {
                    required: true,
                    message: '请输入通知类型',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '状态',
                prop: 'status',
                span: 12,
                addDisplay: false,
                editDisplay: false,
                viewDisplay: true,
                type: 'select',
                dicData: [
                  { label: '待处理', value: 1 },
                  { label: '已处理', value: 2 }
                ]
              },
              {
                label: '事件负责人',
                prop: 'principalName',
                type: 'search',
                searchType: 'input',
                appendClick: () => {
                  this.openUserCommonModal({
                    type: 'sjxxPrincipalName'
                  });
                }
              },
              {
                label: '截止时间',
                prop: 'deadlineTime',
                type: 'datetime',
                span: 12,
                format: 'yyyy-MM-dd HH:mm:ss',
                valueFormat: 'yyyy-MM-dd HH:mm:ss'
              },
              {
                label: '发起人',
                prop: 'creator',
                addDisplay: false,
                editDisplay: false,
                viewDisplay: true
              },
              {
                label: '发起时间',
                prop: 'createTime',
                addDisplay: false,
                editDisplay: false,
                viewDisplay: true,
                type: 'date',
                format: 'yyyy-MM-dd HH:mm:ss',
                valueFormat: 'yyyy-MM-dd HH:mm:ss'
              },
              {
                label: '事件内容',
                prop: 'eventContent',
                span: 24,
                rowSpan: 4,
                type: 'textarea',
                maxlength: 200,
                showWordLimit: true,
                rules: [
                  {
                    required: true,
                    message: '请输入事件内容',
                    trigger: 'blur'
                  }
                ]
              }
            ]
          },
          {
            label: '处理信息',
            prop: 'clxx',
            icon: 'el-icon-edit-outline',
            labelWidth: 100,
            display: false,
            column: [
              {
                label: '处理人',
                prop: 'handlerName',
                span: 12,
                rules: [
                  {
                    required: true,
                    message: '请输入处理人',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '处理时间',
                prop: 'handleTime',
                type: 'date',
                span: 12,
                format: 'yyyy-MM-dd HH:mm:ss',
                valueFormat: 'yyyy-MM-dd HH:mm:ss',
                rules: [
                  {
                    required: true,
                    message: '请输入处理时间',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '处理结果',
                prop: 'handleResult',
                span: 24,
                rowSpan: 4,
                type: 'textarea',
                rules: [
                  {
                    required: true,
                    message: '请输入处理结果',
                    trigger: 'blur'
                  }
                ]
              }
            ]
          }
        ]
      },
      defaults: {},
      data: [],
      modalName: '', //打开公用模态框名称
      visibile: false,
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime() //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.eventRegister_add, false),
        viewBtn: this.vaildData(this.permission.eventRegister_view, false),
        delBtn: this.vaildData(this.permission.eventRegister_delete, false),
        editBtn: this.vaildData(this.permission.eventRegister_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
    });
  },
  methods: {
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.searchDeadlineTime && params.searchDeadlineTime.length > 1) {
        params.startTime = params.searchDeadlineTime[0];
        params.endTime = params.searchDeadlineTime[1];
        delete params.searchDeadlineTime;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleManages(row, index) {
      this.rowData = structuredClone(row);
      this.manageDialog.visible = true;
    },
    beforeOpen(done, type) {
      if (['edit', 'add'].includes(type)) {
        this.option.group[2].display = false;
      } else {
        this.option.group[2].display = this.rowData.status === 2;
      }
      done();
    },
    handleDetail(row, index) {
      this.rowData = structuredClone(row);
      this.$refs.crud.rowView(row, index);
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      // const { releaseTimeRange } = this.query;
      // let values = {
      //   ...params
      // };
      // if (releaseTimeRange) {
      //   values = {
      //     ...params,
      //     releaseTime_datege: releaseTimeRange[0],
      //     releaseTime_datelt: releaseTimeRange[1],
      //     ...this.query
      //   };
      //   // values.releaseTimeRange = null;
      // }
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },

    openUserCommonModal(params) {
      let { type } = params;
      switch (type) {
        // 事件负责人
        case 'principalName':
          this.modalName = 'principalNameModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择事件负责人（双击进行选择）',
            url: '/api/blade-system/user/page',
            isPage: true,
            rowSelectionType: 'single',
            menu: false,
            editBtn: false,
            menuWidth: 100,
            searchLabelWidth: 90,
            templateName: 'USER'
          };
          break;
        // 发起人
        case 'creator':
          this.modalName = 'creatorModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择发起人（双击进行选择）',
            url: '/api/blade-system/user/page',
            isPage: true,
            rowSelectionType: 'single',
            menu: false,
            editBtn: false,
            menuWidth: 100,
            searchLabelWidth: 90,
            templateName: 'USER'
          };
          break;
        // 事件信息 - 事件负责人
        case 'sjxxPrincipalName':
          this.modalName = 'sjxxPrincipalNameModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择事件负责人（双击进行选择）',
            url: '/api/blade-system/user/page',
            isPage: true,
            rowSelectionType: 'single',
            menu: false,
            editBtn: false,
            menuWidth: 100,
            searchLabelWidth: 90,
            templateName: 'USER'
          };
          break;
        // 事件处理弹框 处理人
        case 'manageClr':
          this.modalName = 'manageClrModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择处理人（双击进行选择）',
            url: '/api/blade-system/user/page',
            isPage: true,
            rowSelectionType: 'single',
            menu: false,
            editBtn: false,
            menuWidth: 100,
            searchLabelWidth: 90,
            templateName: 'USER'
          };
          break;
        case 'workshop':
          this.modalName = 'workshopModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择车间信息',
            url: '/api/mes-admin/workshop/page',
            isPage: true,
            rowSelectionType: 'single',
            menuWidth: 100,
            templateName: 'WORKSHOP'
          };
          break;
        case 'line':
          this.modalName = 'lineModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择产线（双击进行选择）',
            url: '/api/mes-product/productionline/page',
            isPage: true,
            rowSelectionType: 'single',
            menu: false,
            editBtn: false,
            menuWidth: 100,
            searchLabelWidth: 90,
            templateName: 'LINE'
          };
          break;
        default:
          break;
      }
    },
    // 获取选择的物料模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'principalNameModal':
          this.search.principalName = this._get(rowData, 'realName', '');
          this.search.principalId = this._get(rowData, 'id', '');
          break;
        case 'creatorModal':
          this.search.creator = this._get(rowData, 'realName', '');
          this.search.createUser = this._get(rowData, 'id', '');
          break;
        case 'sjxxPrincipalNameModal':
          this.form.principalName = this._get(rowData, 'realName', '');
          this.form.principalId = this._get(rowData, 'id', '');
          break;
        case 'manageClrModal':
          this.$set(this.manageDialog.form, 'handlerName', this._get(rowData, 'realName', ''));
          this.$set(this.manageDialog.form, 'handlerId', this._get(rowData, 'id', ''));
          break;
        case 'workshopModal':
          this.form.workshopName = this._get(rowData, 'name', '');
          this.form.workshopId = this._get(rowData, 'id', '');
          break;
        case 'lineModal':
          this.form.lineName = this._get(rowData, 'name', '');
          this.form.lineId = this._get(rowData, 'id', '');
          break;
        default:
          break;
      }
    },
    manageSave() {
      this.$refs.manageForm.submit();
    },
    handleSubmit(form, done) {
      form.id = this.rowData.id;
      handleEvent(form)
        .then(() => {
          this.manageDialog.visible = false;
          this.$refs.manageForm.resetForm();
          this.onLoad(this.page);
        })
        .catch((err) => {})
        .finally(() => {
          done();
        });
    },
    manageCancel() {
      this.$refs.manageForm.resetForm();
    },
    handleReset() {
      this.manageDialog.visible = false;
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style></style>
